package org.eiahe.hr.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.eiahe.hr.interview.domain.*;
import org.eiahe.hr.interview.domain.vo.InterviewBehaviorTestRecordsVO;
import org.eiahe.hr.interview.service.*;
import org.eiahe.hr.interview.domain.dto.InterviewBehaviorTestRecordsQueryDTO;
import org.eiahe.hr.interview.domain.dto.InterviewRecordResultDTO;
import org.eiahe.hr.interview.mapper.InterviewBehaviorTestRecordsMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author :zhangnn
 * @className :InterviewBehaviorTestRecordsServiceImpl
 * @description: TODO
 * @date 2025-08-20 14:47:13
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InterviewBehaviorTestRecordsServiceImpl
    extends ServiceImpl<InterviewBehaviorTestRecordsMapper, InterviewBehaviorTestRecords>
    implements InterviewBehaviorTestRecordsService {

    private final InterviewBehaviorOptionsService behaviorOptionsService;
    private final InterviewCandidateService candidateService;
    private final InterviewQuestionBankService bankService;
    private final InterviewRecordService recordService;


    /**
     * 分页
     * @param queryDTO
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<InterviewBehaviorTestRecordsVO> behaviorTestRecords(InterviewBehaviorTestRecordsQueryDTO queryDTO, PageQuery pageQuery) {
        List<Long> userIds = new ArrayList<>();
        if (StringUtils.isNotBlank(queryDTO.getUserName())) {
            userIds = candidateService.list(new QueryWrapper<InterviewCandidate>().lambda()
                .like((InterviewCandidate::getName), queryDTO.getUserName()))
                .stream().map(InterviewCandidate::getId)
                .collect(Collectors.toList());
        }
        List<Long> bankIds = new ArrayList<>();
        if(StringUtils.isNotBlank(queryDTO.getBankName())){
            bankService.list(new QueryWrapper<InterviewQuestionBank>().lambda()
                .like(InterviewQuestionBank::getBankName,queryDTO.getBankName()))
                .stream().map(InterviewQuestionBank::getId)
                .collect(Collectors.toList());
        }
        LambdaQueryWrapper<InterviewBehaviorTestRecords> lqw = new LambdaQueryWrapper<>();
        lqw.in(StringUtils.isNotBlank(queryDTO.getUserName()),InterviewBehaviorTestRecords::getUserId,userIds);
        lqw.in(StringUtils.isNotBlank(queryDTO.getBankName()),InterviewBehaviorTestRecords::getBankId,bankIds);
        lqw.orderByDesc(InterviewBehaviorTestRecords::getCreateTime);

        IPage<InterviewBehaviorTestRecordsVO> page = this.baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (InterviewBehaviorTestRecordsVO record : page.getRecords()) {
            record.setBankName(bankService.getById(record.getBankId()).getBankName());
            record.setUserName(candidateService.getById(record.getUserId()).getName());
        }
        return TableDataInfo.build(page);
    }

    /**
     * 根据code查看结果
     * @param code
     * @return
     */
    @Override
    public InterviewBehaviorTestRecords selectByCode(String code) {
        return this.baseMapper.selectOne(new QueryWrapper<InterviewBehaviorTestRecords>().lambda()
            .eq(InterviewBehaviorTestRecords::getResultCode,code));
    }

    @Override
    public List<InterviewBehaviorTestRecordsVO> queryList(Long candidateId, Long bankId) {
        List<InterviewBehaviorTestRecordsVO> list =  this.baseMapper.selectVoList(new QueryWrapper<InterviewBehaviorTestRecords>().lambda()
            .eq(InterviewBehaviorTestRecords::getUserId,candidateId)
            .eq(InterviewBehaviorTestRecords::getBankId,bankId)
            .orderByDesc(InterviewBehaviorTestRecords::getCreateTime)
        );
        return list;
    }

    /**
     * 保存行为分析能力测试结果
     * @param recordDTO
     */
    @Override
    public boolean insertTestRecords(InterviewRecordResultDTO recordDTO) {
        InterviewBehaviorTestRecords tr = new InterviewBehaviorTestRecords();
        tr.setUserId(String.valueOf(recordDTO.getCandidateId()));
        tr.setBankId(recordDTO.getBankId());
        tr.setTenantId(LoginHelper.getTenantId());
        //计算结果
        calculateAndSaveResult(tr,recordDTO);
        this.baseMapper.insert(tr);

        //更新面试者面试题库信息
        InterviewRecord record = recordService.getById(recordDTO.getId());
        record.setBankId(recordDTO.getBankId());
        recordService.updateById(record);
        return true;
    }

    public InterviewBehaviorTestRecords calculateAndSaveResult(InterviewBehaviorTestRecords record,InterviewRecordResultDTO request) {
        // 1. 初始化四个维度的得分
        int eIScore = 0;  // E-I维度
        int sNScore = 0;  // S-N维度
        int tFScore = 0;  // T-F维度
        int jPScore = 0;  // J-P维度

        // 2. 遍历用户选择的选项，累加得分
        for (Long optionId : request.getSelectedOptions()) {
            // 查询选项详情（包含dimension_type和score_value）
            InterviewBehaviorOptions option = behaviorOptionsService.getById(optionId);
            if (option == null) {
                throw new IllegalArgumentException("无效的选项ID：" + optionId);
            }

            // 根据维度类型累加得分（每个选项的score_value均为1，只需区分维度）
            switch (option.getDimensionType()) {
                case "E":
                    eIScore += option.getScoreValue();
                    break;
                case "I":
                    eIScore -= option.getScoreValue();  // I与E反向计分
                    break;
                case "S":
                    sNScore += option.getScoreValue();
                    break;
                case "N":
                    sNScore -= option.getScoreValue();  // N与S反向计分
                    break;
                case "T":
                    tFScore += option.getScoreValue();
                    break;
                case "F":
                    tFScore -= option.getScoreValue();  // F与T反向计分
                    break;
                case "J":
                    jPScore += option.getScoreValue();
                    break;
                case "P":
                    jPScore -= option.getScoreValue();  // P与J反向计分
                    break;
                default:
                    throw new IllegalArgumentException("无效的维度类型：" + option.getDimensionType());
            }
        }

        // 3. 根据得分判定MBTI类型（参考之前的规则）
        String resultCode = calculateMbtiType(eIScore, sNScore, tFScore, jPScore);

        // 4. 保存结果到测试记录表
        record.setResultCode(resultCode);
        record.setEIScore(eIScore);
        record.setSNScore(sNScore);
        record.setTFScore(tFScore);
        record.setJPScore(jPScore);
        record.setTenantId("000000");

        return record;
    }

    /**
     * 根据四个维度得分计算MBTI类型
     */
    private String calculateMbtiType(int eIScore, int sNScore, int tFScore, int jPScore) {
        String ei = eIScore > 0 ? "E" : "I";
        String sn = sNScore > 0 ? "S" : "N";
        String tf = tFScore > 0 ? "T" : "F";
        String jp = jPScore > 0 ? "J" : "P";
        // 同分默认规则（如I、N、F、P）
        if (eIScore == 0) ei = "I";
        if (sNScore == 0) sn = "N";
        if (tFScore == 0) tf = "F";
        if (jPScore == 0) jp = "P";
        return ei + sn + tf + jp;
    }
}
